package com.java.com.syun.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class BIOServer {
    public static void main(String[] args) throws Exception {
        ServerSocket server = null;
        try {
            server = new ServerSocket();
            server.bind(new InetSocketAddress(9000));
            while (true) {
                //客户端每一个socket创建一个线程
                Socket socket = server.accept();
                // 启动请求处理线程
                new Thread(new syun.nacos.dubbo.service.HandleTask(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            server.close();
        }
    }
}

class HandleTask implements Runnable {

    private Socket socket;

    public HandleTask(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        InputStream in = null;
        OutputStream out = null;
        try {
            // 读数据
            in = socket.getInputStream();
            byte[] buffer = new byte[1024];
            while (in.read(buffer) != -1) {
                System.out.println(Thread.currentThread().getName() + "读取请求数据：>> " + new String(buffer));
            }
            // 写数据
            out = socket.getOutputStream();
            out.write("World".getBytes());
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOCloseUtils.close(out,in);
        }
    }
}
